package com.bidianying.service;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.bidianying.dao.GewaraDao;



@Service
public class CityIpService {
	
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private GewaraDao gewaraDao;
	
	public String getCityByIp(String ip){
		String url = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
		try{
			String urlStr = restTemplate.getForObject(url,String.class);
			JSONObject jsonObject = JSONObject.fromObject(urlStr);
			if(jsonObject.getInt("code")==1){
				return "";
			}
			JSONObject jsonData = jsonObject.getJSONObject("data");
			String cityName = jsonData.getString("city");
			String cityId = jsonData.getString("city_id");
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap.put("cityName", cityName);
			resultMap.put("cityId", cityId);
			return cityId;
		}catch(Exception e){
			return "";
		}
	}
	
	public String getCityNameById(String citycode){
		Map<String,Object> map = gewaraDao.getCityNameById(citycode);
		if(!map.get("city_name").equals("") && map.get("city_name")!=null){
			return map.get("city_name").toString();
		}
		return "";
	}
	
	
}
